package com.ykc.helper;

import com.ykc.bean.Handler;
import com.ykc.bean.Request;
import com.ykc.spring.Controller;
import com.ykc.spring.RequestMapping;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Ykc
 * @date 2021年05月25日 15:02
 * @description 表现层助手类，相当于SpringMVC里的映射处理器, 为请求URI设置对应的处理器
 */
public class ControllerHelper {

    private static Map<Request, Handler> REQUEST_MAP=new HashMap<>();

    static {
        //获取所有被Controller注解的类
        Set<Class<?>> controllerClassSet=ClassHelper.getControllerClassSet();
        if (CollectionUtils.isNotEmpty(controllerClassSet)){
            for (Class<?> controllerClass:controllerClassSet){
                //通过反射获取所有的方法
                Method[] methods=controllerClass.getDeclaredMethods();
                //遍历所有方法
                if (ArrayUtils.isNotEmpty(methods)){
                    for (Method method:methods){
                        //如果该方法被RequestMapping注解
                        if (method.isAnnotationPresent(RequestMapping.class)){
                            RequestMapping requestMappingAnnotation=method.getAnnotation(RequestMapping.class);
                            //获取请求路径
                            String requestPath = requestMappingAnnotation.value();
                            //获取请求方法
                            String requestMethod=requestMappingAnnotation.method().name();
                            //封装请求与处理器
                            Request request=new Request(requestMethod,requestPath);
                            Handler handler=new Handler(controllerClass,method);
                            REQUEST_MAP.put(request,handler);
                        }
                    }
                }
            }
        }
    }

    /*
     * @author Ykc
     * @date 2021/5/25 15:35
     * @param requestMethod
     * @param requestPath
     * @return com.com.ykc.bean.Handler
     * @description 获取handler
     */
    public static Handler getHandler(String requestMethod,String requestPath){
        Request request=new Request(requestMethod,requestPath);
        return REQUEST_MAP.get(request);
    }


}
